package com.example.qihuibao.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.res.AssetManager;
import android.provider.Settings;
import android.text.TextUtils;

import com.example.qihuibao.XApplication;
import com.example.qihuibao.module.service.MyAccessibilityService;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CommonUtil {
    //检测是否能够上网
    public static boolean isConnectNetwork() {
        String url = "http://www.baidu.com/";//不要用https
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        HttpResponse response = null;
        try {
            response = client.execute(new HttpGet(url));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {//没连wifi、连wifi有代理但代理不能上网的场景
            e.printStackTrace();
        }
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            try {
                HttpURLConnection mHttpUrlConnection = (HttpURLConnection) new URL(url).openConnection();
                mHttpUrlConnection.setConnectTimeout(5000);// 设置连接超时
                try {
                    mHttpUrlConnection.setRequestMethod("GET");
                    try {
                        if (mHttpUrlConnection.getResponseCode() == 200) {//对需要认证的wifi有效
                            return true;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (ProtocolException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean isConnectNetwork2() {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(5L, TimeUnit.SECONDS)
                .readTimeout(5L, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url("http://www.baidu.com/")
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.code() == 200) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断时间是否在时间段内
     * @param time System.currentTimeMillis()
     * @param strDateBegin 开始时间 00:00:00
     * @param strDateEnd 结束时间 00:05:00
     * @return
     */
    public static boolean isInTime(long time, String strDateBegin, String strDateEnd) {
        Calendar calendar = Calendar.getInstance();
        // 处理开始时间
        String[] startTime = strDateBegin.split(":");
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(startTime[2]));
        calendar.set(Calendar.MILLISECOND, 0);
        long startTimeL = calendar.getTimeInMillis();
        // 处理结束时间
        String[] endTime = strDateEnd.split(":");
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(endTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(endTime[2]));
        calendar.set(Calendar.MILLISECOND, 0);
        long endTimeL = calendar.getTimeInMillis();
        return time >= startTimeL && time <= endTimeL;
    }

    /**
     * 判断时间是否在时间段内
     * @param time System.currentTimeMillis()
     * @param strDateBegin 格式 xx:xx
     * @param strDateEnd 格式 xx:xx
     * @return
     */
    public static boolean isInTime2(long time, String strDateBegin, String strDateEnd) {
        Calendar calendar = Calendar.getInstance();
        // 处理开始时间
        String[] startTime = strDateBegin.split(":");
        if (startTime.length < 2) return false;
        try {
            if (startTime[0].length() >=2 && startTime[0].startsWith("0")) {
                startTime[0] = startTime[0].substring(1);
            }
            if (startTime[1].length() >=2 && startTime[1].startsWith("0")) {
                startTime[1] = startTime[1].substring(1);
            }
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
//        calendar.set(Calendar.SECOND, Integer.parseInt(startTime[2]));
            calendar.set(Calendar.MILLISECOND, 0);
            long startTimeL = calendar.getTimeInMillis();
            // 处理结束时间
            String[] endTime = strDateEnd.split(":");
            if (endTime[0].length() >=2 && endTime[0].startsWith("0")) {
                endTime[0] = endTime[0].substring(1);
            }
            if (endTime[1].length() >=2 && endTime[1].startsWith("0")) {
                endTime[1] = endTime[1].substring(1);
            }
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endTime[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(endTime[1]));
//        calendar.set(Calendar.SECOND, Integer.parseInt(endTime[2]));
            calendar.set(Calendar.MILLISECOND, 0);
            long endTimeL = calendar.getTimeInMillis();
            return time >= startTimeL && time <= endTimeL;
        }catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断时间未到时间段
     * @param time System.currentTimeMillis()
     * @param strDateBegin 格式 xx:xx
     * @return
     */
    public static boolean beforeTime(long time, String strDateBegin) {
        Calendar calendar = Calendar.getInstance();
        // 处理开始时间
        String[] startTime = strDateBegin.split(":");
        if (startTime.length < 2) return false;
        try {
            if (startTime[0].length() >=2 && startTime[0].startsWith("0")) {
                startTime[0] = startTime[0].substring(1);
            }
            if (startTime[1].length() >=2 && startTime[1].startsWith("0")) {
                startTime[1] = startTime[1].substring(1);
            }
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
//        calendar.set(Calendar.SECOND, Integer.parseInt(startTime[2]));
            calendar.set(Calendar.MILLISECOND, 0);
            long startTimeL = calendar.getTimeInMillis();
            return time < startTimeL;
        }catch (Exception e) {
            return false;
        }
    }

    //时分秒转毫秒
    public static long time2Millis(String time) {
        String[] startTime = time.split(":");
        if (startTime.length < 3) {
            return System.currentTimeMillis();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(startTime[2]));
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    //毫秒转时分秒
    public static String millis2Time(long mss) {
        long second = mss/1000;
        long hours = second / 3600;
        long minutes = (second - hours*3600) / 60;
        long seconds = second - hours*3600 - minutes*60;
        return hours/10+""+hours%10+":"+minutes/10+""+minutes%10+":"+seconds/10+""+seconds%10;
    }

//    public static org.json.JSONObject getParams(org.json.JSONObject data) {
//        org.json.JSONObject params = new org.json.JSONObject();
//        try {
//            params.put("data", encryptBase64ByRsaPublicKey(data.toString(), Config.PUBLIC_KEY));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return params;
//    }

    /**
     * RSA公钥加密
     *
     * @param data          被加密的字符串
     * @param publicKey     RSA私钥
     *
     * @return Base64字符串密文
     */
    public static String encryptBase64ByRsaPublicKey(String data, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.encryptBase64(data, KeyType.PublicKey);
    }

    //RSA解密
    public static String decryptBase64ByRsaPublicKey(String data, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.decryptStr(data, KeyType.PublicKey);
    }

    //检查app是否已经运行
    public static boolean ifAppProcessExit(Context context, String pkgName) {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(pkgName) && info.baseActivity.getPackageName().equals(pkgName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        final String service = mContext.getPackageName() + "/" + MyAccessibilityService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
//            LogUtil.INSTANCE.e("accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
//            LogUtil.INSTANCE.e("Error finding setting, default accessibility to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
//            LogUtil.INSTANCE.e("***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

//                    LogUtil.INSTANCE.e("-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
//                        LogUtil.INSTANCE.e("We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
//            LogUtil.INSTANCE.e("***ACCESSIBILITY IS DISABLED***");
        }

        return false;
    }

    public static String getObjFromAssetsJson(String fileName) {
        try {
            // 获取AssetManager对象
            AssetManager assetManager = XApplication.application.getAssets();
            // 打开指定路径的json文件并返回InputStream流
            InputStream inputStream = assetManager.open(fileName);
            // 创建BufferedReader对象来读取数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            // 关闭reader和inputStream
            reader.close();
            inputStream.close();
            // 将StringBuilder转换成字符串
            return stringBuilder.toString();
            // 这里可以根据自己的需求对jsonData进行处理
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 检查是否非法输入
     * @param s
     * @return
     */
    public static boolean inputIllegal(String s) {
        if (s == null || s.isEmpty()) {
            return true;
        }
        return CalculateUtils.calculate(s) <= 0;
    }

}
